package com.woniuxy.service.impl;

import com.woniuxy.entity.Comment;
import com.woniuxy.mapper.BlogMapper;
import com.woniuxy.mapper.CommentMapper;
import com.woniuxy.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private BlogMapper blogMapper;

    @Override
    @Transactional // 确保操作在同一事务中
    public void add(Comment comment) {
        // 插入评论（自增ID会自动回填到comment对象）
        commentMapper.add(comment);

        // 如果originId为空，更新为当前评论ID
        if (comment.getOriginId() == null) {
            System.out.println("originId为空，更新为当前评论ID"+comment.getId());
            commentMapper.updateOriginIdIfNull(comment.getId());
        }

        // 更新blog评论的数量 comment_count+1
        blogMapper.plusOneCommentCount(comment.getItemId());

    }

    @Override
    public Integer count(Integer userId) {
        return commentMapper.count(userId);
    }

    @Override
    public Integer findCommentOriginIdById(Integer pid) {
        return commentMapper.findCommentOriginIdById(pid);
    }

    /**
     * 构建评论树（从平级列表递归组装）
     * @param flatList 平级评论列表
     * @param parentId 父评论ID（顶级为 0）
     * @return 树形结构评论列表
     */
    @Override
    public List<Comment> buildTree(List<Comment> flatList, Integer parentId) {
        List<Comment> tree = new ArrayList<>();
        for (Comment comment : flatList) {
            if (comment.getPid().equals(parentId)) {
                // 查找子评论
                List<Comment> children = flatList.stream()
                        .filter(c -> c.getPid().equals(comment.getId()))
                        .collect(Collectors.toList());
                comment.setChildren(children);
                tree.add(comment);
                // 递归处理子评论
                buildTree(children, comment.getId());
            }
        }
        return tree;
    }

    @Override
    @Transactional // 确保操作在同一事务中
    public void deleteCommentById(Comment comment) {
        // 根据id删除评论
        commentMapper.deleteCommentById(comment.getId());
        // 删除成功后，更新blog的评论数量 comment_count-1
        blogMapper.subtractOneCommentCount(comment.getItemId());
    }
}





